<template>
  <el-dialog :visible.sync="show" :title="title"
             width="800" show-footer>
    <template #default>
      <div v-loading="loading">
        <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            :multiple="multiple"
            :on-change="onchange"
            :auto-upload="false">
          <template #trigger>
            <el-button type="primary" ref="selectFiles">选择文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">
              当前文件：<span style="color: red">{{ fileList.length }}个</span>
              ，已成功上传：<span style="color: green">{{ okIndex }}个</span>
            </div>
          </template>
          <template #file="{file}">
            <div style="padding: 6px;font-size: 15px;border-bottom:1px solid #caced0">
              {{ file.name }}
              <span style="float: right">
            {{ file.percentCompleted ? file.percentCompleted : '未上传' }}
            <el-button type="primary" size="small" @click="uploadFile(getFile(file.uid))">上传</el-button>
            <el-button type="danger" size="small" @click="fileList.splice(getFile(file.uid),1)"
                       v-if="file.percentCompleted == '上传失败'">删除</el-button>
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="file.message"
                  placement="right"
              >
        <el-button v-if="file.message" size="small">原因</el-button>
      </el-tooltip>
          </span>
            </div>
          </template>
        </el-upload>
      </div>
    </template>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="uploadFile" :loading="loading">全部上传</el-button>
    </template>
  </el-dialog>
</template>

<script>

import {upload} from "@/utils/http/httpUtils";
import {error, success} from "@/utils/msg";

export default {
  name: 'olDialogUploadFile',
  inject: ['http'],
  data() {
    return {
      title: '上传文件',
      show: false,
      fileList: [],
      okIndex: 0,
      multiple: true,
      loading: true,
      url: '',
      autoClose: false,
    }
  },
  methods: {
    getFile(uid) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == uid) {
          return i;
        }
      }
    },
    onchange(file, fileList) {
      this.fileList = fileList;
      if (this.multiple == false) {
        this.uploadFile();
      } else {
        this.loading = false;
      }
    },
    async uploadFile(index) {
      if (this.fileList.length == 0) {
        error("请选择文件！");
        return;
      }
      let length = this.fileList.length;
      let i = 0;
      let thIndex = index == undefined ? 0 : index;

      this.loading = true;
      while (i < length) {
        let file = this.fileList[thIndex];
        file.percentCompleted = 0;
        const formData = new FormData();
        formData.append('files', file.raw);
        await upload(this.http, this.url, formData, progressEvent => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) /
              progressEvent.total)
          file.percentCompleted = percentCompleted + "%";
        }).then(({code, msg}) => {
          if (code == 200) {
            this.okIndex++;
            this.fileList.splice(thIndex, 1)
          } else {
            file.percentCompleted = "上传失败";
            file.message = msg;
            thIndex++;
          }
        })
            .catch(error => {
              thIndex++;
              // 上传失败处理逻辑
              console.error('上传失败', error);
            });
        if (index != undefined) {
          break
        }
        i++;
      }
      this.loading = false;
      if (this.multiple == false && this.okIndex == 0) {
        success("上传失败！")
      } else {
        success("上传成功！")
        if (this.autoClose || this.multiple == false) {
          this.show = false;
        }
      }

    },
    close() {
      this.show = false;
      let args = {}
      if (this.okIndex != 0) {
        args.m = 'query'
      }
      this.$emit("emits", args);
    },
    init(obj) {
      this.fileList = [];
      this.okIndex = 0;
      let {url, title, autoClose, multiple} = obj;
      if (!url) {
        url = obj;
      }
      if (!url) {
        error("请填写上传文件url!");
        return
      }
      this.show = true;
      this.url = url;
      this.title = title ? title : this.title;
      this.autoClose = autoClose != undefined ? autoClose : this.autoClose;
      this.multiple = multiple != undefined ? multiple : this.multiple;
      this.$nextTick(() => {
        this.$refs.selectFiles.$el.click();
        setTimeout(() => {
          this.loading = false;
        }, 300)
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-upload-list {
  overflow-x: auto;
  height: 300px;
}
</style>
